
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-row>
            <el-col :span="5">
              <el-form-item label="订单状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
                  <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="适用地区" prop="province">
                <el-select
                  v-model="queryParams.province"
                  placeholder="请选择"
                  clearable
                  size="small"
                  remote
                  filterable
                  :remote-method="remoteMethod"
                  :loading="selectload"
                >
                  <el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="订单编号" prop="order_number">
                <el-input
                  v-model="queryParams.order_number"
                  placeholder="请输入标题"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="9" class="itemStyle">
              <el-form-item label="提交时间">
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model="queryParams.phone"
                  placeholder="请输入标题"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="发货人员" prop="deliver_id">
                <el-select v-model="queryParams.deliver_id" filterable placeholder="请选择发货人">
                  <el-option
                    v-for="item in userArray"
                    :key="item.user_id"
                    :label="item.nick_name"
                    :value="item.user_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="9" class="itemStyle">
              <el-form-item label="发货时间">
                <el-date-picker
                  v-model="deliveryDateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </el-form-item>
            </el-col>
            <el-form-item style="float:right">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-row>
        </el-form>

        <el-button class="mb10" type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        <div style="display: flex">
          <div style="margin-right: 10px">订单总数：{{ total }}</div>
          <div>订单总金额：{{ $Prices(sum) }}（元）</div>
        </div>
        <el-table
          v-loading="loading"
          :data="sysOrderList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" header-align="center" width="50" label="序号" fixed="left" align="center" />
          <el-table-column header-align="center" :show-overflow-tooltip="true" label="订单编号" fixed="left">
            <template slot-scope="scope">
              <span>{{ scope.row.order_number }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column header-align="center" prop="subject" label="科目" />
          <el-table-column header-align="center" prop="province" label="适用地区" />-->
          <el-table-column label="订单金额" header-align="center" align="left" prop="price" width="100">
            <template slot-scope="scope">
              <span class="text-price">{{ $Prices(scope.row.price) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单返佣" header-align="center" align="left" prop="commission" width="100">
            <template slot-scope="scope">
              <span class="text-price">{{ $Prices(scope.row.commission) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="customer" label="关联上级" header-align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.customer && scope.row.customer.recommenders">{{ scope.row.customer.recommenders.name
              }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" header-align="center" align="left" prop="status">
            <template slot-scope="scope">
              <el-tag :type="tagType(scope.row.status)">{{ tagStatus(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="买家信息" header-align="center" align="left" prop="customer">
            <template slot-scope="scope">
              <span>{{ scope.row.customer ? scope.row.customer.name : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="买家号码"
            header-align="center"
            align="left"
            prop="customer"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.customer ? scope.row.customer.phone : '' }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="教师信息"
            header-align="center"
            align="left"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.teacher ? scope.row.teacher.name : '' }}</span>
            </template>
          </el-table-column>-->
          <el-table-column label="提交时间" align="center" prop="createdAt" width="155px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发货时间" align="center" prop="send_at" width="155px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.send_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发货人" align="center" prop="deliver_id">
            <template slot-scope="scope">
              <span>{{ scope.row.DeliverUser ? scope.row.DeliverUser.nickName : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="140" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-row :gutter="10">
                <el-col :span="1.5">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    :disabled="scope.row.status !== 3"
                    @click="handleUpdate(scope.row)"
                  >发货</el-button>
                </el-col>
                <el-col :span="1.5">
                  <router-link :to="{ name: 'OrderView', params: { id: scope.row.id, type: 'material' } }">
                    <el-button size="mini" type="text" icon="el-icon-view">查看</el-button>
                  </router-link>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>

      <OrderAction
        :visible="visible"
        :list="logisticsList"
        @fall-back="fallBack"
        @on-visible-change="onVisibleChange"
      />
    </template>
  </BasicLayout>
</template>

<script>
import {
  materialOrderList,
  courierCompany,
  deliverGoods
} from '@/api/admin/sys-order'
import OrderAction from '../components/action.vue'
import { materialStatusOptions, getTagType, getStatus } from '../utils'
import { formatJson, prices } from '@/utils'
import { parseTime } from '@/utils/costum'
import { getCity, getUserList } from '@/api/admin/sys-course'
export default {
  name: 'SysOrderMaterialManage',
  components: { OrderAction },
  data() {
    return {
      statusOptions: materialStatusOptions,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      sum: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      visible: false,
      sysOrderList: [],
      dateRange: [],
      deliveryDateRange: [],
      logisticsList: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        status: undefined,
        province: undefined,
        order_number: undefined,
        begin_time: undefined,
        end_time: undefined,
        phone: undefined,
        deliver_id: undefined
      },
      cityList: [],
      selectload: false,
      userArray: []
    }
  },
  created() {
    getUserList().then(res => {
      this.userArray = res?.data
    })
    this.getList()
    this.fetchCourierCompany()
    getCity().then(res => {
      this.cityList = res?.data || []
    })
  },
  methods: {
    tagType(status) {
      return getTagType('material', status)
    },
    tagStatus(status) {
      return getStatus('material', status)
    },
    getList() {
      this.loading = true
      try {
        materialOrderList(this.addDateRange({
          ...this.queryParams,
          start_send_time: this.deliveryDateRange?.[0] || undefined,
          end_send_time: this.deliveryDateRange?.[1] || undefined
        }, this.dateRange))
          .then(response => {
            this.sysOrderList = response.data.list
            this.total = response.data.count
            this.sum = response.data.sum ?? 0
          })
          .finally(() => {
            this.loading = false
          })
      } catch (error) {
        console.log(error)
      }
    },
    // 获取快递公司
    fetchCourierCompany() {
      courierCompany().then(res => {
        if (res.code === 200) {
          this.logisticsList = res.data ?? []
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    parentIdFormat(row) {
      return this.selectItemsLabel(this.parentIdOptions, row.parentId)
    },
    // 文件
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.deliveryDateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.consult_wz_id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = row
      this.visible = true
    },
    onVisibleChange(v) {
      this.visible = v
    },
    fallBack(values) {
      // 发货
      deliverGoods({
        ...values,
        id: this.form.id
      }).then(response => {
        if (response.code !== 200) {
          this.msgError(response.msg)
          return
        }
        this.visible = false
        this.form = {}
        this.getList()
        this.msgSuccess(response.msg)
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams
      this.$confirm('是否确认导出所有参数数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            '订单编号',
            '科目',
            '适用地区',
            '订单金额',
            '订单返佣',
            '关联上级',
            '订单状态',
            '买家信息',
            '教师信息',
            '提交时间',
            '发货时间'
          ]
          const filterVal = [
            'order_number',
            'subject',
            'province',
            'price',
            'commission',
            'customer',
            'status',
            'center',
            'teach',
            'createdAt',
            'send_at'
          ]
          const list = this.sysOrderList.map(item => {
            return {
              order_number: item?.order_number,
              subject: item?.subject,
              province: item?.province,
              price: prices(item?.price),
              commission: prices(item?.commission),
              customer: item?.customer ? item?.customer?.name : '',
              status: this.tagStatus(item.status),
              center: item?.customer ? item?.customer?.name : '',
              teach: item?.customer
                ? item?.customer?.teach_recommenders?.username
                : '',
              createdAt: parseTime(item?.createdAt)
            }
          })
          const data = formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '资料订单',
            autoWidth: true, // Optional
            bookType: 'xlsx' // Optional
          })
          this.downloadLoading = false
        })
      })
    }
  }
}
</script>

<style lang="scss">
.box-card {
  .el-row {
    .el-col-5 {
      .el-form-item {
        margin-right: 0;

        .el-form-item__content {
          width: 70%;
        }
      }
    }
  }
}
</style>
